//
//  OrderHasPaidViewController.m
//  SXH
//
//  Created by Jack on 15/12/21.
//  Copyright © 2015年 lyss. All rights reserved.
//

#import "OrderHasPaidViewController.h"
#import "CommonService.h"
#import "UIButton+WebCache.h"
#import "OrderProductEntity.h"
#import "LocalProductDetailViewController.h"
#import "RouteDetailViewController.h"
#import "OrderEntity.h"
#import "OrderTableViewCell.h"
#import "OrderDetailViewController.h"
#import "CommentOrderViewController.h"
#import "OrderCancelViewController.h"

@interface OrderHasPaidViewController (){
    MJRefreshHeaderView *_header;
    MJRefreshFooterView *_footer;
    int page;
    NSString *userId;
    NSString *order_id;
}
@property (nonatomic, strong) NSMutableArray *mutableArrayOrderHasPaid;
@property (nonatomic, strong) IBOutlet UITableView *tableViewOrderHasPaid;

@end

@implementation OrderHasPaidViewController
@synthesize mutableArrayOrderHasPaid,tableViewOrderHasPaid;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    mutableArrayOrderHasPaid = [[NSMutableArray alloc]init];
    UserEntity *userEntity = [UserEntity sharedInstance];
    userId = userEntity.userId;
    page=1;
    [self addHeader];
    [self addFooter];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark -
#pragma mark Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return [mutableArrayOrderHasPaid count];
}

#pragma mark - tableView headView
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40.0;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    headView.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:1];
    
    UIImage *image = [UIImage imageNamed:@"店铺.png"];
    UIImageView *businessLogo = [[UIImageView alloc] initWithFrame:CGRectMake(10, 12, 15, 15)];
    [businessLogo setImage:image];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 0, 250, 40)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.textColor = [UIColor darkGrayColor];
    titleLabel.font = [UIFont systemFontOfSize:13];
    
    UIImage *imageArrow = [UIImage imageNamed:@"右_02.png"];
    UIImageView *arrowView = [[UIImageView alloc] initWithFrame:CGRectMake(300, 12, 15, 15)];
    [arrowView setImage:imageArrow];
    
    UILabel *orderTagLabel = [[UILabel alloc] initWithFrame:CGRectMake(headView.frame.size.width-60, 0, 150, 40)];
    orderTagLabel.backgroundColor = [UIColor clearColor];
    orderTagLabel.textColor = [UIColor darkGrayColor];
    orderTagLabel.font = [UIFont systemFontOfSize:13];
    
    if([mutableArrayOrderHasPaid count] >0){
        OrderEntity *entity = [mutableArrayOrderHasPaid objectAtIndex:section];
        titleLabel.text = ([entity.store_name isEqualToString:@""])?@"乐游山水网络科技有限公司":entity.store_name;
        orderTagLabel.text = ([entity.status isEqualToString:@"104"])?@"已完成":@"已付款";
        if ([entity.status isEqualToString:@"104"]&&[entity.can_comment isEqualToString:@"1"]) {
            orderTagLabel.text = @"已评价";
        }
    }
    
    [headView addSubview:businessLogo];
    [headView addSubview:titleLabel];
    //[headView addSubview:arrowView];
    [headView addSubview:orderTagLabel];
    
    return headView;
}

#pragma mark - tableView footView
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 50.0;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 90)];
    footView.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:1];//[UIColor blackColor];
    
//    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width-10, 39)];
//    titleLabel.backgroundColor = [UIColor clearColor];
//    titleLabel.textColor = [UIColor darkGrayColor];
//    titleLabel.font = [UIFont systemFontOfSize:13];
//    titleLabel.textAlignment = NSTextAlignmentRight;
    
    UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 1)];
    lineLabel.backgroundColor = [UIColor colorWithRed:0.95 green:0.93 blue:0.92 alpha:1];
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGColorRef colorref = CGColorCreate(colorSpace,(CGFloat[]){ 0.9, 0.9, 0.9, 1 });
    UIButton *orderDelete =[[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width-90, 5, 80, 30)];
    [orderDelete.layer setCornerRadius:5.0]; //设置矩形四个圆角半径
    [orderDelete.layer setBorderWidth:1.0]; //边框宽度
    [orderDelete.layer setBorderColor:colorref];//边框颜色
    orderDelete.titleLabel.font = [UIFont systemFontOfSize: 14.0];
    [orderDelete setTitleColor:[UIColor blackColor]forState:UIControlStateNormal];

    
    UIButton *orderComment =[[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width-175, 5, 80, 30)];
    [orderComment.layer setCornerRadius:5.0]; //设置矩形四个圆角半径
    [orderComment.layer setBorderWidth:1.0]; //边框宽度
    [orderComment.layer setBorderColor:colorref];//边框颜色
    orderComment.titleLabel.font = [UIFont systemFontOfSize: 14.0];
    [orderComment setTitleColor:[UIColor blackColor]forState:UIControlStateNormal];
    [orderComment setTitle:@"评论" forState:UIControlStateNormal];
    [footView addSubview:orderComment];

    
    UILabel *lineLabel2 = [[UILabel alloc] initWithFrame:CGRectMake(0, 40, self.view.frame.size.width, 1)];
    lineLabel2.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1];
    
    UILabel *lineLabel3 = [[UILabel alloc] initWithFrame:CGRectMake(0, 41, self.view.frame.size.width, 10)];
    lineLabel3.backgroundColor = [UIColor colorWithRed:0.95 green:0.93 blue:0.92 alpha:1];
    
    if([mutableArrayOrderHasPaid count] >0){
        OrderEntity *entity = [mutableArrayOrderHasPaid objectAtIndex:section];
//        titleLabel.text = [NSString stringWithFormat:@"%@%@%@%@%@",@"合计: ¥ ",entity.total_amount,@" (含运费: ¥ ",entity.ship_cost,@")"];
        [orderDelete addTarget:self action:@selector(deleteOrder:) forControlEvents:UIControlEventTouchUpInside];
        orderDelete.tag = [entity.ID integerValue];
        orderComment.tag = [entity.ID integerValue];
        if ([entity.status isEqualToString:@"104"]&&[entity.can_comment isEqualToString:@"2"]) {
            orderComment.hidden = NO;
            [orderComment addTarget:self action:@selector(commentOrder:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        else if([entity.status isEqualToString:@"102"])
        {
            orderDelete.hidden = YES;
            if ([entity.can_cancel isEqualToString:@"1"]) {
                orderComment.hidden = NO;
                orderComment.frame = CGRectMake(self.view.frame.size.width-90, 5, 80, 30);
                [orderComment setTitle:@"退单" forState:UIControlStateNormal];
                [orderComment addTarget:self action:@selector(cancleOrder:) forControlEvents:UIControlEventTouchUpInside];
            }
            else
            {
                orderComment.hidden = YES;
            }

        }
        else
        {
            orderComment.hidden = YES;
        }
    }
    
//    [footView addSubview:titleLabel];
    [footView addSubview:lineLabel];
   
    [orderDelete setTitle: @"删除" forState: UIControlStateNormal];
    [footView addSubview:orderDelete];
    [footView addSubview:lineLabel2];
    
    return footView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *couponTableViewCellIdentifier=@"OrderTableViewCell";
    OrderTableViewCell *cell = (OrderTableViewCell *)[tableView dequeueReusableCellWithIdentifier:couponTableViewCellIdentifier];
    if (cell == nil) {
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"OrderTableViewCell" owner:self options:nil];
        cell = [array objectAtIndex:0];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
//    if([mutableArrayOrderHasPaid count] > 0){
//        NSLog(@"indexPath is = %li",(long)indexPath.section);
//        OrderEntity *entity = [mutableArrayOrderHasPaid objectAtIndex:indexPath.section];
//        
//        for (int i = 0; i < [entity.product_list count]; i++) {
//            OrderProductEntity *productEntity = [entity.product_list objectAtIndex:i];
//            cell.productName.text = productEntity.product_name;
//            [cell.productImage sd_setImageWithURL:[NSURL URLWithString:productEntity.album_thumb] forState:UIControlStateNormal];
//            cell.introduce.text = productEntity.introduce;
//            cell.goodsCnt.text = [NSString stringWithFormat:@"%@%@",@"x ",productEntity.count];
//            cell.price.text = [NSString stringWithFormat:@"¥%@",productEntity.price];
//            cell.priceLabel.text = [NSString stringWithFormat:@"¥%@",entity.total_amount];
//            cell.total_peopleLabel.text = [NSString stringWithFormat:@"%@",[productEntity.tourism_data objectForKey:@"total_people"]]; ;
//            cell.departure_dateLabel.text = [productEntity.tourism_data objectForKey:@"departure_date"];
//        }
//    }
    if([mutableArrayOrderHasPaid count] > 0){
        NSLog(@"indexPath is = %li",(long)indexPath.section);
        OrderEntity *entity = [mutableArrayOrderHasPaid objectAtIndex:indexPath.section];
        
        for (int i = 0; i < [entity.product_list count]; i++) {
            OrderProductEntity *productEntity = [entity.product_list objectAtIndex:i];
            cell.productName.text = productEntity.product_name;
            //            [cell.productImage sd_setBackgroundImageWithURL:[NSURL URLWithString:productEntity.album_thumb] forState:UIControlStateNormal];
            [cell.productImage sd_setImageWithURL:[NSURL URLWithString:productEntity.album_thumb] forState:UIControlStateNormal];
            cell.introduce.text = productEntity.introduce;
            cell.goodsCnt.text = [NSString stringWithFormat:@"%@%@",@"x ",productEntity.count];
            cell.price.text = [NSString stringWithFormat:@"¥%@",productEntity.price];
        }
    }

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 95;
}

#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    RouteDetailViewController *rvc=[[RouteDetailViewController alloc]init];
    LocalProductDetailViewController *lpvc=[[LocalProductDetailViewController alloc]init];
    OrderEntity *orderEntity = [mutableArrayOrderHasPaid objectAtIndex:indexPath.section];
    OrderProductEntity *productEntity = [orderEntity.product_list objectAtIndex:0];
    NSString *product_id=productEntity.product_id;
    if([orderEntity.order_class isEqualToString:@"1"]){
        RouteEntity *routeEntityTemp=[[RouteEntity alloc]init];
        routeEntityTemp.t_id=product_id;
        rvc.routeEntity = routeEntityTemp;
        [self.navigationController pushViewController:rvc animated:YES];
    }else if([orderEntity.order_class isEqualToString:@"2"]){
        LPEntity *wrapEntityTemp=[[LPEntity alloc]init];
        wrapEntityTemp.ID = product_id;
        lpvc.wrapEntity = wrapEntityTemp;
        [self.navigationController pushViewController:lpvc animated:YES];
    }
    else if ([orderEntity.order_class isEqualToString:@"0"])
    {
        OrderDetailViewController *mvc = [[OrderDetailViewController alloc]init];
        mvc.order_id = orderEntity.ID;
        mvc.pre_vc = self;
        mvc.order_entity = orderEntity;
        [self.navigationController pushViewController:mvc animated:YES];
    }
}

- (void) getOrderData:(int) pageNo RefreshView:(MJRefreshBaseView *)refreshView {
    
    NSString *strPageNo = [NSString stringWithFormat:@"%d", pageNo];
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           userId, @"user_id",
                           @"102", @"status",
                           strPageNo, @"page",
                           @"10", @"limit",nil];
    
    [service getNetWorkData:param
                       Path:USER_QUERY_ORDER_new
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      if (pageNo == 1) {
                          [mutableArrayOrderHasPaid removeAllObjects];
                      }
                      NSArray *array = [dic objectForKey:@"rows"];
                      for (NSDictionary* attributes in array) {
                          OrderEntity *orderEntity = [[OrderEntity alloc] init];
                          orderEntity = [orderEntity initWithAttributes:attributes];
                          [mutableArrayOrderHasPaid addObject:orderEntity];
                      }
                      
                      dispatch_async(dispatch_get_main_queue(), ^{
                          [self doneWithView:refreshView];
                          tableViewOrderHasPaid.hidden = ([mutableArrayOrderHasPaid count] == 0)?YES:NO;
                          [tableViewOrderHasPaid reloadData];
                      });
                      
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      DebugLog(@"%@", message);
                      [self doneWithView:refreshView];
                  }];
}

- (void)addFooter
{
    //__unsafe_unretained OAAnnoViewController *vc = self;
    MJRefreshFooterView *footer = [MJRefreshFooterView footer];
    footer.scrollView = self.tableViewOrderHasPaid;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        
        ++page;
        [self getOrderData:page RefreshView:refreshView];
        
        NSLog(@"%@----开始进入刷新状态", refreshView.class);
    };
    _footer = footer;
}

- (void)addHeader
{
    //__unsafe_unretained OAAnnoViewController *vc = self;
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = self.tableViewOrderHasPaid;
    
    header.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        // 进入刷新状态就会回调这个Block
        [self getOrderData:1 RefreshView:refreshView];
        NSLog(@"%@----开始进入刷新状态", refreshView.class);
    };
    header.endStateChangeBlock = ^(MJRefreshBaseView *refreshView) {
        // 刷新完毕就会回调这个Block
        NSLog(@"%@----刷新完毕", refreshView.class);
    };
    header.refreshStateChangeBlock = ^(MJRefreshBaseView *refreshView, MJRefreshState state) {
        // 控件的刷新状态切换了就会调用这个block
        switch (state) {
            case MJRefreshStateNormal:
                NSLog(@"%@----切换到：普通状态", refreshView.class);
                break;
                
            case MJRefreshStatePulling:
                NSLog(@"%@----切换到：松开即可刷新的状态", refreshView.class);
                break;
                
            case MJRefreshStateRefreshing:
                NSLog(@"%@----切换到：正在刷新状态", refreshView.class);
                break;
            default:
                break;
        }
    };
    [header beginRefreshing];
    _header = header;
}

- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    // 刷新表格
    [self.tableViewOrderHasPaid reloadData];
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}

//去掉UItableview headerview黏性(sticky)
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.tableViewOrderHasPaid)
    {
        CGFloat sectionHeaderHeight = 60; //sectionHeaderHeight
        if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
        } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
        }
    }
}

//删除订单
-(void)deleteOrder:(UIButton*)btn{
    order_id=[NSString stringWithFormat:@"%ld",(long)btn.tag];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"删除订单" message:@"是否要删除该订单？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.tag = 90012;
    [alert show];
}

-(void)commentOrder:(UIButton*)btn{
    CommentOrderViewController *mvc = [[CommentOrderViewController alloc]init];
    mvc.order_id = [NSString stringWithFormat:@"%ld",(long)btn.tag];
    mvc.pre_vc = self;
    [self.navigationController pushViewController:mvc animated:YES];
}


-(void)cancleOrder:(UIButton*)btn{
    OrderCancelViewController *mvc = [[OrderCancelViewController alloc]init];
    mvc.order_id = [NSString stringWithFormat:@"%ld",(long)btn.tag];
    mvc.pre_vc = self;
    [self.navigationController pushViewController:mvc animated:YES];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 90012) {
        if (buttonIndex == 1) {
            [self deletePaidOrder];
        }
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];



}


-(void)deletePaidOrder{
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           userId, @"userid",
                           order_id, @"order_id",nil];
    
    [service getNetWorkData:param
                       Path:USER_ORDER_DELETE
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      if([[dic objectForKey:@"code"] integerValue] == 0){
                          [_header beginRefreshing];
                      }else{
                          ALERT_ERR_MSG(@"删除失败，请稍后重试！");
                      }
                      
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      DebugLog(@"%@", message);
                      ALERT_ERR_MSG(@"删除失败，请稍后重试！");
                  }];

}

@end
